export default class Timer {
  constructor() {
    this.timerId = null;
    this.interval = 0;
    this.remaining = 0;
    this.callback = null;

    this.running = false;   // 是否已启动
    this.paused = false;    // 是否暂停
    this.startTime = 0;
  }

  /**
   * 设置任务（不自动开始）
   */
  setTask(callback, interval) {
    this.callback = callback;
    this.interval = interval;
    this.remaining = interval;
  }

  /**
   * run = start + resume
   * 如果从未开始 → 启动
   * 如果暂停状态 → 恢复
   */
  run() {
    if (!this.callback || !this.interval) {
      console.warn("请先调用 setTask(callback, interval)");
      return;
    }

    // 如果是暂停状态 → 恢复
    if (this.paused) {
      this.paused = false;
      this.startTime = Date.now();
      this._run();
      return;
    }

    // 否则（第一次启动）
    this.stop(); // 清理旧任务
    this.running = true;
    this.paused = false;

    this.remaining = this.interval;
    this.startTime = Date.now();

    this._run();
  }

  _run() {
    this.timerId = setTimeout(() => {
      if (!this.running) return;

      this.callback && this.callback();

      this.remaining = this.interval;
      this.startTime = Date.now();

      this._run();
    }, this.remaining);
  }

  /**
   * 暂停计时
   */
  pause() {
    if (!this.running || this.paused) return;

    this.paused = true;
    clearTimeout(this.timerId);

    const now = Date.now();
    this.remaining -= (now - this.startTime);
  }

  /**
   * 停止计时（完全重置）
   */
  stop() {
    this.running = false;
    this.paused = false;

    clearTimeout(this.timerId);
    this.timerId = null;

    this.remaining = 0;
  }
}
